package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enmus.HuanXinMessageType;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanHuaService {
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private QuestionService questionService;
    @Reference(version = "1.0.0",check = false)
    private HuanXinApi huanXinApi;
    @Reference(version = "1.0.0",check = false)
    private VisitorsApi visitorsApi;
    @Reference(version = "1.0.0",check = false)
    private UserLocationApi userLocationApi;
    @Value("${tanhua.default.recommend.users}")
    private String moruser;
    @Reference(version = "1.0.0",check = false)
    private UserLikeApi userLikeApi;
    @Autowired
    private IMService imService;



    public TodayBest queryUserInfo(Long userId) {
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        if(ObjectUtil.isEmpty(userInfo))
            return null;
        User getuser = UserThreadLocal.getuser();
        TodayBest todayBest = new TodayBest();
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setId(userId);
        todayBest.setTags(userInfo.getTags().split(","));
        //缘分值
        todayBest.setFateValue(recommendUserService.queryScore(userId,getuser.getId()).longValue());
        todayBest.setAge(userInfo.getAge());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setAvatar(userInfo.getLogo());
        //保存来访用户
        visitorsApi.saveVisitor(userId,getuser.getId(),"个人主页");
        return todayBest;


    }

    public String queryQuestion(Long userId) {
        Question question = questionService.queryQuestion(userId);
        if(ObjectUtil.isEmpty(question))
            return "你的爱好是什么？";
        return question.getTxt();

    }

    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.getuser();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId());
        msg.put("huanXinId", "HX_" + user.getId());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);
        //发送环信消息
        return this.huanXinApi.sendMsgFromAdmin("HX_" + userId,
                HuanXinMessageType.TXT, JSONUtil.toJsonStr(msg));
    }

    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //查询当前用户的位置
        Long id = UserThreadLocal.getuser().getId();
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(id);
        if(ObjectUtil.isEmpty(userLocationVo))
            return null;
        PageInfo<UserLocationVo> userLocationVoPageInfo = userLocationApi.queryUserFromLocation(userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Double.parseDouble(distance), 1, 50);
        List<UserLocationVo> records = userLocationVoPageInfo.getRecords();
        if(CollUtil.isEmpty(records))
            return null;
        //构造筛选条件
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> userWrapper = new QueryWrapper<>();
        userWrapper.in("user_id",userIdList);
        if(gender.equals("man"))
            userWrapper.eq("sex", 1);
        if(gender.equals("woman"))
            userWrapper.eq("sex", 2);
        List<UserInfo> userInfos = userInfoService.queryUserInfoList(userWrapper);
        ArrayList<NearUserVo> objects = new ArrayList<>();
        for (UserLocationVo u:records) {
            if(ObjectUtil.equals(u.getUserId(), id)){
                //排除自己
                continue;
            }
            for (UserInfo a:userInfos) {
                if (u.getUserId() == a.getUserId()) {
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setUserId(a.getUserId());
                    nearUserVo.setNickname(a.getNickName());
                    nearUserVo.setAvatar(a.getLogo());
                    objects.add(nearUserVo);
                    break;
                }

            }
        }
        return objects;


    }
    /**
     * 查询推荐卡片列表，从推荐列表中随机选取10个用户
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.getuser();
        int count = 50;
        List<RecommendUser> recommendUserList = this.recommendUserService.queryCardList(user.getId(), count);
        if(CollUtil.isEmpty(recommendUserList))
        {
            String[] split = StrUtil.split(moruser, ",");
            for (String a:split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(a));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);

            }
        }
        int min = Math.min(10, recommendUserList.size());
        List<RecommendUser> result = new ArrayList<>();
        for (int i = 0; i < min; i++) {
            int i1 = RandomUtils.nextInt(0, recommendUserList.size());
            result.add(recommendUserList.get(i1));
        }
        List<Object> userId = CollUtil.getFieldValues(result, "userId");
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByUserIdList(userId);
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }

        return todayBests;


    }

    public boolean likeUser(Long likeUserId) {
        User getuser = UserThreadLocal.getuser();
        Boolean aBoolean = userLikeApi.likeUser(getuser.getId(), likeUserId);
        if(!aBoolean)
            return false;
        if (this.userLikeApi.isMutualLike(getuser.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;



    }

    public boolean notLikeUser(Long likeUserId) {
        User getuser = UserThreadLocal.getuser();
        return  userLikeApi.notLikeUser(getuser.getId(),likeUserId);
    }
}
